<template>
  <div>

    <el-card class="box-card">

      <div slot="header" class="clearfix">
        <span class="containerTitle">计费规则</span>
        <el-button plain size="mini" @click="handleOpen" type="primary" v-hasPermi="['contract:rules:add']">新增
        </el-button>
        <el-button plain size="mini" @click="handleEdit" type="warning" v-hasPermi="['contract:rules:edit']"
                   :disabled="single">编辑
        </el-button>
        <el-button plain size="mini" @click="handleDelete" type="danger" v-hasPermi="['contract:rules:remove']"
                   :disabled="multiple">删除
        </el-button>
        <el-button plain size="mini" @click="showTotalTree1" type="success">预览
        </el-button>
      </div>

      <el-table :data="dataList" fit border style="width: 100%" @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55" align="center" fixed/>

        <el-table-column prop="ruleId" label="ID" align="center" show-overflow-tooltip width="80"/>

        <el-table-column label="业务类型" align="center" show-overflow-tooltip width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.project_type" :value="scope.row.projectType"/>
          </template>
        </el-table-column>

        <el-table-column prop="projectId" label="服务名称" align="center" :formatter="projectFeeFormat"
                         show-overflow-tooltip width="200"/>

        <el-table-column prop="unitPrice" label="单价" align="center" show-overflow-tooltip/>

        <el-table-column label="币种" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.currency" :value="scope.row.currency"/>
          </template>
        </el-table-column>

        <el-table-column prop="taxRate" label="税点" align="center" show-overflow-tooltip/>

        <el-table-column label="是否自动计费" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAuto"/>
          </template>
        </el-table-column>

        <el-table-column prop="decimalNum" label="小数位数" align="center" show-overflow-tooltip/>

        <el-table-column label="保留小数方法" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.decimal_method" :value="scope.row.decimalMethod"/>
          </template>
        </el-table-column>

        <el-table-column prop="createBy" label="创建人" align="center" show-overflow-tooltip/>

        <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip/>

        <el-table-column prop="updateBy" label="更新人" align="center" show-overflow-tooltip/>

        <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip/>

        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template slot-scope="scope">
            <!--            <el-button type="text" size="small" @click="handleQueryRules(scope.row)">查看规则</el-button>-->
            <el-button icon="el-icon-edit" type="text" size="small" @click="handleEditRules(scope.row)"
                       v-if="scope.row.isAuto == 'Y'" v-hasPermi="['contract:rules:edit']">编辑规则明细
            </el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-card>

    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>

      <el-form :model="form" ref="rulesForm" :inline="true" label-width="120px" :rules="rules">

        <el-form-item label="业务类型" prop="projectType">
          <el-select v-model="form.projectType" placeholder="请选择" @change="getProjectFeeOptions"
                     style="width: 200px">
            <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="服务名称" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择" @change="setTaxRate" style="width: 200px">
            <el-option v-for="item in projectFeeOptions" :key="item.projectFeeId" :label="item.projectFeeName"
                       :value="item.projectFeeId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="币种" prop="currency">
          <el-select v-model="form.currency" placeholder="请选择" style="width: 200px">
            <el-option v-for="item in dict.type.currency" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="税点" prop="taxRate">
          <el-input v-model="form.taxRate" placeholder="请输入" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="是否自动计费" prop="isAuto">
          <el-select v-model="form.isAuto" placeholder="请选择" style="width: 200px">
            <el-option v-for="item in dict.type.sys_yes_no" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="小数位数" prop="decimalNum">
          <el-input v-model="form.decimalNum" placeholder="请输入" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="保留小数方法" prop="decimalMethod">
          <el-select v-model="form.decimalMethod" placeholder="请选择" style="width: 200px">
            <el-option v-for="item in dict.type.decimal_method" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog title="预览规则" :visible.sync="showTotalTree" append-to-body width="55%" :close-on-click-modal="false">
      <SimpleMindMap :mindData="totalTree"></SimpleMindMap>
    </el-dialog>

    

    <!--    <show-iframe-dialog-->
    <!--      ref="showIceConfigDialog"-->
    <!--      :iframe-url="iceConfigUrl"-->
    <!--      :dialog-titile="'编辑规则'"-->
    <!--    ></show-iframe-dialog>-->


    <el-dialog title="编辑规则" :visible.sync="showIceConfig" append-to-body width="98%" @closed="clearIceId"
               :close-on-click-modal="false">
      <ice-rules @ruleChange="handleQuery" :rule-id="ruleId" v-if="ruleId != null"/>
    </el-dialog>


  </div>
</template>

<script>
import {
  addConRules, delRules,
  editConRules,
  getConRulesById,
  getConRulesList, getIceConf, getIceUrl, labelProjectFeeByConId,
  labelProjectTypeByConId, listIceConf
} from "@/api/contract/rules";
import {labelProjectFee, optionProjectFee} from "@/api/base/project";
import {delSerial, getSerial} from "@/api/base/serial";
import ShowIframeDialog from "@/views/components/showIframeDialog/ShowIframeDialog.vue";
import IceRules from "@/views/contract/rules/iceRules";
import SimpleMindMap from "@/components/SimpleMindMap/Index.vue";

export default {
  name: "ConRules",
  components: {SimpleMindMap, IceRules, ShowIframeDialog},
  props: ['calConId'],
  dicts: ['project_type', 'currency', 'sys_yes_no', 'decimal_method'],
  data() {
    return {
      showTotalTree: false,
      totalTree: {
        "root": {
          "data": {
            "text": "合同",
            "expand": true,
            "isActive": false
          },
          "children": []
        },
        "theme": {},
        "layout": "logicalStructure",
        "config": {},
        "view": {
          "transform": {
            "scaleX": 1,
            "scaleY": 1,
            "shear": 0,
            "rotate": 0,
            "translateX": -300,
            "translateY": -100,
            "originX": 0,
            "originY": 0,
            "a": 1,
            "b": 0,
            "c": 0,
            "d": 1,
            "e": -300,
            "f": -100
          },
          "state": {
            "scale": 1,
            "x": -300,
            "y": -100,
            "sx": 0,
            "sy": 0
          }
        }
      },
      conId: this.calConId,
      dataList: [],
      loading: false,
      total: 0,
      queryForm: {
        conId: this.calConId,
        pageNum: 1,
        pageSize: 10
      },

      projectTypeOptions:[],//根据 合同id 获取的 业务类型

      projectFeeOptions:[],//根据 业务类型 获取的 服务名称

      projectFeeOptionsAll:[],

      open:false,
      title:'',
      form:{
        ruleId:null,
        conId:this.calConId,
        iceId:null,
        projectId:null,
        currency:null,
        taxRate:null,
        createBy:null,
        createTime:null,
        updateBy:null,
        updateTime:null,
        projectType:null,
        isAuto:null,
        unitPrice:null,
        decimalNum:null,
        decimalMethod:null,
      },

      ids:[],
      single:true,
      multiple:true,

      rules:{
        projectType: [
          { required: true, message: "业务类型不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "服务名称不能为空", trigger: "blur" }
        ],
        currency: [
          { required: true, message: "币种不能为空", trigger: "blur" }
        ],
        isAuto:{
          required: true, message: "是否自动计费不能为空", trigger: "blur"
        },
      },

      iceConfigUrl:'',
      showIceConfig:false,
      ruleId:null,
    }
  },
  created() {

    // this.getProjectTypeOptions()

    this.getProjectFeeOptionsAll()

    this.handleQuery();

  },
  methods: {
    showTotalTree1() {
      this.showTotalTree = true
    },
    async getAllRuleTreeData() {
      var totalTreeData={
        "root": {
          "data": {
            "text": "合同",
            "expand": true,
            "isActive": false
          },
          "children": []
        },
        "theme": {},
        "layout": "logicalStructure",
        "config": {},
        "view": {
          "transform": {
            "scaleX": 1,
            "scaleY": 1,
            "shear": 0,
            "rotate": 0,
            "translateX": -300,
            "translateY": -100,
            "originX": 0,
            "originY": 0,
            "a": 1,
            "b": 0,
            "c": 0,
            "d": 1,
            "e": -300,
            "f": -100
          },
          "state": {
            "scale": 1,
            "x": -300,
            "y": -100,
            "sx": 0,
            "sy": 0
          }
        }
      }
      for (var i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].isAuto==='Y')
        {
          await getIceConf(this.dataList[i].ruleId).then(res => {
            var iceShowNode = [];
            iceShowNode.push(res.root)
            var ruleTreeJsonData = IceRules.methods.changeIceShowNodeIntoJson(iceShowNode)
            totalTreeData.root.children.push(ruleTreeJsonData.root)
          })
        }
      }
      this.totalTree = totalTreeData
      console.log(this.totalTree)
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleQuery(){
      this.queryForm.pageNum = 1
      this.getList()
    },

    getList() {
      this.loading = true
      getConRulesList(this.queryForm).then(res => {
        this.dataList = res.rows
        this.getAllRuleTreeData()
        this.total = res.total
        this.loading = false
      })
    },

    getProjectTypeOptions(){
      let query = {
        conId:this.conId
      }

      labelProjectTypeByConId(query).then(res=>{
        this.projectTypeOptions = res.data
      })

    },

    getProjectFeeOptions(val){

      this.form.projectId = null
      this.form.taxRate = null

      let query = {
        projectType:val
      }
      labelProjectFee(query).then(res=>{
        this.projectFeeOptions = res.data
      })
    },

    setTaxRate(val){

      //根据 val 遍历 projectFeeOptions 获取 taxRate
      this.projectFeeOptions.forEach(item=>{
        if(item.projectFeeId === val){
          this.form.taxRate = item.taxRate
        }
      })

    },

    getProjectFeeOptionsAll(){
      optionProjectFee().then(res=>{
        this.projectFeeOptionsAll = res.data
      })
    },

    handleOpen(){
      this.getProjectTypeOptions()
      this.open = true
      this.title = '新增规则'
    },

    handleEdit(row){
      this.getProjectTypeOptions()
      this.reset();
      const id = row.id || this.ids
      labelProjectFeeByConId(id).then(res=>{
        this.projectFeeOptions = res.data
      })
      getConRulesById(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流水号";
      });
    },

    projectFeeFormat(row,col){
      return this.selectDictLabel(this.projectFeeOptionsAll,row.projectId)
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        ruleId:null,
        conId:this.calConId,
        iceId:null,
        projectId:null,
        currency:null,
        taxRate:null,
        createBy:null,
        createTime:null,
        updateBy:null,
        updateTime:null,
        projectType:null,
        isAuto:null,
        unitPrice:null,
        decimalNum:null,
        decimalMethod:null,
      };
      this.resetForm("rulesForm");
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["rulesForm"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != null) {
            editConRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除ID为"' + ids + '"的数据项？').then(function() {
        return delRules(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleQueryRules(row){

      if(row.iceId !== null){
        let query = {
          iceId:row.iceId
        }
        listIceConf(query).then(res=>{
          console.log(res)
        })
      }else {
        this.$modal.msgError('该规则不是自动计费')
      }

    },

    // 点击编辑规则
    handleEditRules(row){

      if(row.isAuto == 'Y'){



        this.ruleId = row.ruleId

        this.showIceConfig = true




      }else {
        this.$modal.msgError('该规则不是自动计费')
      }

    },

    clearIceId(){
      // location.reload();
      this.ruleId = null
    },


  }
}
</script>

<style scoped>

.containerTitle {
  font-size: 18px;
  color: #409EFF;
  margin-right: 20px;
}

</style>
